import { setToken, getToken, removeToken } from '@/utils/auth'
import { getUserInofAPI, loginAPI } from '@/api/user'
// 状态
const state = {
  // token: null
  token: getToken(),
  // 用户基本信息
  userInfo: {}
}
// 同步任务:将token存储到state
const mutations = {
  setUserToken(state, token) {
    state.token = token
    setToken(token)
  },
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
  removeUserToken(state) {
    state.token = null
    removeToken()
  }
}
// 异步任务:发送登录请求，得到token
const actions = {
  async loginAction(context, loginForm) {
    const token = await loginAPI(loginForm)
    context.commit('setUserToken', token)
  },

  async  getUserInofAction(context) {
    const userInfo = await getUserInofAPI()
    context.commit('setUserInfo', userInfo)
  },
  logoutAction(context) {
    context.commit('removeUserToken')
    context.commit('setUserInfo', {})
  }
}
export default {
  // 注意点：Vuex在划分模块时，必写命名空间
  namespaced: true,
  state,
  mutations,
  actions
}

